What is TypeScript?
TypeScript is a superset of JavaScript that adds static typing to the language. It compiles down to plain JavaScript, making it compatible with all JavaScript environments.
TypeScript helps catch errors during development, improves code readability, and enhances tooling support (e.g., autocompletion, refactoring).
Why Use TypeScript?
Here are some key reasons why JavaScript developers should consider TypeScript:
-
Static Typing: Catch errors at compile time rather than runtime.
-
Better Tooling: Enhanced IDE support with autocompletion, type checking, and refactoring tools.
-
Improved Readability: Explicit types make code easier to understand and maintain.
-
Scalability: TypeScript is ideal for large-scale projects with multiple developers.
-
JavaScript Compatibility: TypeScript is a superset of JavaScript, so all valid JavaScript code is valid TypeScript.
Setting Up TypeScript
Before diving into TypeScript, you need to set up your environment.
Step 1: Install TypeScript
You can install TypeScript globally using npm:
npm install -g typescript
Step 2: Create a TypeScript File
Create a file with a .ts extension, e.g., app.ts.
Step 3: Compile TypeScript to JavaScript
Use the TypeScript compiler (tsc) to compile your .ts file into .js:
tsc app.ts
This will generate an app.js file that you can run using Node.js or in the browser.
TypeScript Basics
1. Type Annotations
TypeScript allows you to explicitly define types for variables, function parameters, and return values.
let message: string = "Hello, TypeScript!";
let count: number = 42;
let isActive: boolean = true;
2. Functions
You can define types for function parameters and return values:
function add(a: number, b: number): number {
return a + b;
}
3. Interfaces
Interfaces define the structure of an object:
interface User {
id: number;
name: string;
email: string;
}
const user: User = {
id: 1,
name: "John Doe",
email: "john@example.com",
};
4. Classes
TypeScript supports object-oriented programming with classes:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return `Hello, my name is ${this.name}`;
}
}
const person = new Person("Alice", 30);
console.log(person.greet());
Advanced TypeScript Features
1. Union and Intersection Types
-
Union Types: Allow a variable to hold values of multiple types.
let value: string | number; value = "Hello"; value = 42; -
Intersection Types: Combine multiple types into one.
interface A { a: string; } interface B { b: number; } type C = A & B; const obj: C = { a: "hello", b: 42 };
2. Generics
Generics allow you to create reusable components that work with multiple types:
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("Hello");
let output2 = identity<number>(42);
3. Enums
Enums allow you to define a set of named constants:
enum Color {
Red,
Green,
Blue,
}
let color: Color = Color.Red;
4. Type Aliases
Type aliases allow you to create custom types:
type StringOrNumber = string | number;
let value: StringOrNumber;
value = "Hello";
value = 42;
5. Decorators
Decorators are a special kind of declaration that can be attached to classes, methods, or properties:
function log(target: any, key: string) {
console.log(`Method ${key} was called`);
}
class Calculator {
@log
add(a: number, b: number): number {
return a + b;
}
}
TypeScript with Modern JavaScript
TypeScript works seamlessly with modern JavaScript features like ES6+ syntax, modules, and async/await.
Example: Using Async/Await
async function fetchData(): Promise<void> {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
}
TypeScript Configuration
TypeScript uses a tsconfig.json file to configure compiler options. Here’s an example:
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true,
"outDir": "./dist"
},
"include": ["src/**/*"]
}
Key options:
-
target: The JavaScript version to compile to (e.g., ES6). -
module: The module system to use (e.g., CommonJS, ES6). -
strict: Enables strict type checking. -
outDir: The output directory for compiled files.
TypeScript Tooling
-
VS Code: The best editor for TypeScript, with built-in support for type checking, autocompletion, and debugging.
-
ts-node: Run TypeScript files directly without compiling:
npx ts-node app.ts -
ESLint: Lint your TypeScript code for style and best practices.